package it.storm.solution;

/**
 * 795. 区间子数组个数
 * https://leetcode-cn.com/problems/number-of-subarrays-with-bounded-maximum/
 */
public class Solutions_795 {
    public static void main(String[] args) {
        int[] nums = {2, 1, 4, 3};
        int L = 2, R = 3;  // output: 3

        int result = numSubarrayBoundedMax(nums, L, R);
        System.out.println(result);
    }

    public static int numSubarrayBoundedMax(int[] A, int L, int R) {
        // 小于等于 R 的子数组数量 - 小于 L 的子数组数量 = 大于等于 L 并且小于等于 R 的子数组数量
        return counts(A, R) - counts(A, L - 1);
    }

    public static int counts(int[] nums, int bound) {
        int cur = 0, ans = 0;
        for (int num : nums) {
            cur = num <= bound ? cur + 1 : 0;
            // {2, 1}，小于等于 2 的子数组有 3 个，即 {{2}, {1}, {2, 1}}
            ans += cur;
        }
        return ans;
    }
}
